﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using DCS.CaclulationClient;
using DCS.CalculationClient.DCS_Service;
using DCS.Extensions.WindowsForms;

namespace DCS.CalculationClient.View
{
    public partial class MainForm : Form
    {   
        private readonly Model model;

        public ProgressForm StopCalculatingForm = new ProgressForm
                                                        {
                                                            Header = "Остановка",
                                                            Message = "Вычисления останавливаются ..."
                                                        };
        public HardwareDescription Me;
        public MainForm(Model model)
        {
            InitializeComponent();
            this.model = model;
        }

        private void BackgroundCalculatorDoWork(object sender, DoWorkEventArgs e)
        {
            var backgroundWorker = sender as BackgroundWorker;

            if (backgroundWorker != null)
            {
                while (!backgroundWorker.CancellationPending)
                {
                    RefreshClientCharacteristics();

                    Calculate();
                }

                SetStatusLabel("Вычисления остановлены");
                StopCalculatingForm.SafeHide();
            }
        }
        
        private void Calculate()
        {
            model.Calculate();
        }

        private void ButtonStartStopClick(object sender, EventArgs e)
        {
            StartStopClicked();
        }

        public void AddLog(LogRecord record)
        {
            lock (dataGridLog)
            {
                dataGridLog.InvokeSync(
                    () => dataGridLog.Rows.Insert(0, new object[]
                                                         {
                                                             imageListStates.Images[
                                                                 record.State.ToString()],
                                                             record.TaskName,
                                                             record.PortionNumber,
                                                             record.Message,
                                                             record.IsRetransferred 
                                                             ? imageListStates.Images["retransfered"]
                                                             :imageListStates.Images["empty"]
                                                         }));
            }
        }

        public void ChangePortionState(string task, uint portion, TaskPortionState taskPortionState, string message)
        {
            lock (dataGridLog)
            {
                foreach (DataGridViewRow row in dataGridLog.Rows)
                {
                    if ((string)row.Cells["taskName"].Value == task &&
                        Convert.ToUInt32(row.Cells["portionNumber"].Value) == portion)
                    {
                        row.Cells["stateImage"].Value = imageListStates.Images[taskPortionState.ToString()];
                        row.Cells["state"].Value = message;
                    }
                }
            }
        }

        private void MainFormLoad(object sender, EventArgs e)
        {
            RefreshClientCharacteristics();
        }

        private void RefreshClientCharacteristics()
        {
            Me = new HardwareDescription
            {
                Ram = ClientEnvironment.AvailableRAM,
                CpuFrequency = ClientEnvironment.CpuFrequency,
                AvailableMemory = ClientEnvironment.AvailableHDDSpace,
                CoreCount = Environment.ProcessorCount
            };

            textBoxCpu.SafeTextSet(Me.CpuFrequency.ToString());
            textBoxCores.SafeTextSet(Me.CoreCount.ToString());
            textBoxRam.SafeTextSet(Me.Ram.ToString());
            textBoxHdd.SafeTextSet(Me.AvailableMemory.ToString());
        }

        public void SetStatusLabel(string text)
        {
            labelClientState.Text = text;
        }

        public void SetButtonImage(ButtonImage image)
        {
            switch (image)
            {
                case ButtonImage.Start:
                    {
                        buttonStartStop.Image = imageListButtons.Images["start"];
                        break;
                    }
                case ButtonImage.Stop:
                    {
                        buttonStartStop.Image = imageListButtons.Images["stop"];
                        break;
                    }
            }
        }
        public void SetButtonText(string text)
        {
            buttonStartStop.SafeTextSet(text);
        }

        public void SetConnectionImage(bool isConnected)
        {
            labelConnectionState.Image = isConnected
                                             ? imageConnectionStates.Images["connected"]
                                             : imageConnectionStates.Images["disconnected"];
        }
        public void SetConnectionText(string text)
        {
            labelConnectionState.Text = text;
        }

        public event Action StartStopClicked;
    }
}